<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-crad>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="dialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom',il===0?'bdtop':'','vcentter']" v-for="(item1, il) in scope.row.children" :key='item1.id'>
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close='removeRightById(scope.row,item1.id)'>{{ item1.authName }}</el-tag>
                <i class="el-icon-creat-right"></i>
              </el-col>
              <!-- 二级权限 三级权限 -->
              <el-col :span="19">
                <el-row :class="['bdbottom',i2===0?'bdtop':'','vcentter']" v-for="(item2, i2) in item1.children" :key='item2.id'>
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close='removeRightById(scope.row,item2.id)'>{{ item2.authName }}</el-tag>
                    <i class='el-icon-caret-right'></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type='warning' v-for="(item3,i3) in item2.children" :key='item3.id' :key2='i3' closable @close='removeRightById(scope.row,item3.id)'>
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- 弹出对话框 -->
            <el-dialog></el-dialog>
          </template>
        </el-table-column>
        <!-- 主体 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editRoles(scope)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRoles(scope)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightsDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-crad>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisble" width="50%" @close='setRightDialogClosed'>
      <!-- 内容主体区域 -->
              <!-- 树形控件 -->
        <el-tree :data="setRightForm" :props="treeProps" show-checkbox
      node-key='id' default-expand-all :default-checked-keys='defKeys'
      ref='treeRef'>
        </el-tree>
           <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisble = false">取 消</el-button>
        <el-button type="primary" @click="setRight">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加角色" :visible.sync="dialogVisible" width="50%" @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" ref="addFormRef" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog title="修改角色" :visible.sync="dialogEdittVisible" width="50%" @close="editDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="editForm2" ref="editFormRef" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm2.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm2.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogEdittVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 角色数据存放
      roleList: [],
      //  是否打开添加用户对话框
      dialogVisible: false,
      //  是否打开编辑角色
      dialogEdittVisible: false,
      // 是否打开分配权限
      setRightDialogVisble: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      editForm2: {
        id: 0,
        roleName: '',
        roleDesc: ''
      },
      // 分配权限的数据
      setRightForm: [],
      // 树形控件属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 树中默认选中的节点
      defKeys: [],
      // 操作当前用户的id
      roleId: ''
    }
  },
  created () {
    //  页面启动时候家寨数据
    this.getRoleList()
  },
  methods: {
    //   获得角色数据
    async getRoleList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.roleList = res.data
      // console.log(this.roleList)
    },
    // 添加角色
    async addUser () {
      const { data: res } = await this.$http.post('roles', this.addForm)
      //   console.log(res)
      if (res.meta.status !== 201) return this.$message.error('失败')
      this.$message.success(res.data.roleId + ' ' + res.data.roleName + '添加成功了')
      this.dialogVisible = false
      this.getRoleList()
    },
    // 编辑角色
    async editUserInfo () {
      const { data: res } = await this.$http.put('roles/' + this.editForm2.id, this.editForm2)
      console.log(this.editForm2.roleName)
      if (res.meta.status !== 200) return this.$message.error('失败')
      this.$message.success(res.data.roleId + ' ' + res.data.roleName + '修改成功了')
      this.dialogEdittVisible = false
      this.getRoleList()
    },
    // 添加角色对话框取消后 消除内容
    addDialogClosed () {
      this.addForm.roleName = ''
      this.addForm.roleDesc = ''
    },
    // 编辑角色对话框取消后 清理内容
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 编辑按钮触发事件
    editRoles (scope) {
      this.dialogEdittVisible = true
      this.editForm2.roleName = scope.row.roleName
      this.editForm2.roleDesc = scope.row.roleDesc
      this.editForm2.id = scope.row.id
      //   console.log(scope)
    },
    // 删除角色
    async deleteRoles (scope) {
      const { data: res } = await this.$http.delete('roles/' + scope.row.id)
      if (res.meta.status !== 200) return this.$message.error('失败')
      this.$message.success('删除成功')
      this.getRoleList()
    },
    // 根据id删除对应的权限
    async removeRightById (role, rightId) {
      // 提示框
      const confirmResult = await this.$confirm('此操作将永久删除文件，还是否继续', '提示', {
        confirmButtonText: '确定',
        concelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      } else {
        const { data: res } = await this.$http.delete(`roles/${this.roleId}/rights/${rightId}`)
        if (res.meta.status !== 200) {
          return this.message.error('请求删除失败')
        } else {
          // this.getRoleList()
          role.children = res.data
        }
      }
    },
    // 显示分配权限对话框的
    async showSetRightsDialog (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('请求数据失败')
      this.setRightForm = res.data
      // console.log(this.setRightForm)
      // console.log(role.children)
      this.getLeafKeys(role, this.defKeys)
      console.log(this.defKeys)
      this.setRightDialogVisble = true
    },
    // 获取所有的角色下三级权限的id
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 关闭分配权限对话框后清空数据
    setRightDialogClosed () {
      this.defKeys = []
    },
    // 分配权限
    async setRight () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) { return this.$message.error('error connection for https') }
      this.$message.success('divied into power success')

      this.getRoleList()
      this.setRightDialogVisble = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcentter {
  display: flex;
  align-items: center;
}
</style>
